package com.wsu.search.tools;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * <p>
 * Title: 检索基本工具类
 * </p>
 * <p>
 * Description:常用工具
 * </p>
 * <p>
 * Copyright: Copyright (c) pacific 2003
 * </p>
 * <p>
 * Company: pacific
 * </p>
 * 
 * @author wsu
 * @version $Header: /src/com/pacific/search/util/Tools.java,v 1.1.1.1
 *          2003/12/25 17:34:56 ws Exp $
 */

public class Tools
{
	public Tools() {
	}

	/**
	 * 截NULL
	 * 
	 * @param str
	 * @return
	 */
	public static String RmNull(String str)
	{ // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		return str;
	}

	/**
	 * 过滤 $%^*?+_',.等符号
	 * 
	 * @param str
	 * @return
	 */
	public static String RmFilter(String str)
	{ // remove null string
		if (str == null || str.equals("")) {
			str = "";
		}
		String regEx = "[!=~/_)|(#&@!$%^*?+',.-]"; // 表示一个或多个a\p{Punct}

		Pattern p = Pattern.compile(regEx);

		Matcher m = p.matcher(str);

		str = m.replaceAll("");
		
		
		return str;
	}

	/**
	 * 删除网页标签,包括<> 及里面的字符,只留中文
	 * 
	 * @param s
	 *            String
	 * @return String
	 */
	public static String rmHtml(String str)
	{
		if (str == null || str.equals("")) {
			str = "";
		}
		String regEx = "[=\\'^\"./%;&<>(A-Z)(a-z)]"; // 表示一个或多个a\p{Punct}

		Pattern p = Pattern.compile(regEx);

		Matcher m = p.matcher(str);

		str = m.replaceAll("");
		str = str.replaceAll(" ","");
		
		regEx = "[0-9]{5,}";
		p = Pattern.compile(regEx);
		m = p.matcher(str);
		str = m.replaceAll("");
		//System.out.println(str);
		
		return str;
	}
	
	/**
	 * 读文件到缓冲里面
	 * 
	 * @param filePath
	 * @return
	 */
	public static StringBuffer readFile(String filePath)
	{
		// StringBuffer bStr = new StringBuffer();
		// String LineStr = "";
		// try {
		// System.setProperty("user.language", "zh");
		// System.setProperty("file.encoding", "GBK");
		// java.io.FileReader fr = new java.io.FileReader(filePath);
		//
		// java.io.BufferedReader br = new java.io.BufferedReader(
		// fr);
		// while ( (LineStr = br.readLine()) != null) {
		// bStr.append(LineStr +
		// System.getProperty("line.separator"));
		// }
		// br.close();
		// fr.close();
		// }
		// catch (Exception e) {
		// System.out.println(e.getMessage());
		// System.out.println("不能读取正文！");
		// }
		// return bStr;
		try {
			return readFile(filePath,"UTF-8");
		}
		catch (IOException ex) {
			System.out.println(ex);
			return null;
		}
	}

	public static void writeFile(String filePath, String contStr)
	{
		writeFile(filePath,contStr,"UTF-8");
	}

	public static void writeFile(String filePath, String contStr, String encoder)
	{
		try {
			java.io.FileOutputStream afile = new java.io.FileOutputStream(filePath);
			afile.write(contStr.getBytes(encoder));
			afile.close();

		}
		catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println("Can't Written！");
		}
	}

	public static StringBuffer readFile(String filePath, String encoder) throws java.io.IOException
	{
		try {

			java.io.InputStream fis = new java.io.FileInputStream(filePath);
			byte[] b_all = new byte[fis.available()];
			byte[] readBytes = new byte[10240];
			int readInt, start = 0;
			while ((readInt = fis.read(readBytes)) != -1) {
				System.arraycopy(readBytes,0,b_all,start,readInt);
				start += readInt;
			}
			fis.close();
			String str = new String(b_all,encoder);
			return new StringBuffer(str);
		}
		catch (IOException e) {
			System.out.println("read  the file " + filePath + " err:" + e.toString());
			throw e;
		}

	}

	/**
	 * 日期格式化
	 * 
	 * @param date
	 *            需要格式化日期
	 * @param pattern
	 *            需要格式话的PATTERN
	 * @return 返回格式化的效果
	 */
	public static String dateToStr(Date date, String pattern)
	{
		java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat(pattern);
		return formater.format(date);
	}

	/**
	 * 替换字符窜，虽然1。4有功能，但为了能再1。2能用所以用此函数
	 * 
	 * @param source
	 * @param oldString
	 * @param newString
	 * @return
	 */
	public static String Replace(String source, String oldString, String newString)
	{
		StringBuffer output = new StringBuffer(); // define String Buffer
		int lengthOfSource = source.length(); // 源字符串长度
		int lengthOfOld = oldString.length(); // 老字符串长度
		int posStart = 0; // 开始搜索位置
		int pos; // 搜索到老字符串的位置
		while ((pos = source.indexOf(oldString,posStart)) >= 0) {
			output.append(source.substring(posStart,pos));

			output.append(newString);
			posStart = pos + lengthOfOld;
		}

		if (posStart < lengthOfSource) {
			output.append(source.substring(posStart));
		}

		return output.toString();
	}

	public static void mkDir(String filePath)
	{
		File file = new File(filePath);
		try {
			file.mkdirs();
			System.out.println("make dir ok!");
		}
		catch (Exception e) {
			System.out.println("mkdir error:" + e);
		}
	}

	/**
	 * 回车换行
	 * 
	 * @param Content
	 * @return
	 */
	public static String addBR(String Content)
	{
		String makeContent = "";
		StringTokenizer strToken = new StringTokenizer(Content,"\n");
		while (strToken.hasMoreTokens()) {
			makeContent = makeContent + strToken.nextToken() + "<br>";
		}
		makeContent = makeContent.replaceAll("  ","　");
		return makeContent;
	}

	/**
	 * 字符集转换
	 * 
	 * @param s
	 * @return
	 */
	public static String ISO8859_1ToGBK(String s)
	{
		try {
			if (s == null || s.equals("")) {
				s = "";
			}
			 s = new String(s.getBytes("ISO-8859-1"), "UTF-8");
		}
		catch (Exception e) {
			System.out.println("ISO8859_1ToGBK" + e);
		}
		return s;
	}

	/**
	 * 字符集转换
	 * 
	 * @param s
	 * @return
	 */
	public static String GBKToISO8859_1(String s)
	{
		try {
			if (s == null || s.equals("")) {
				s = "";
			}
			 s = new String(s.getBytes("UTF-8"), "ISO-8859-1");
		}
		catch (Exception e) {
			System.out.println("GBKToISO8859_1" + e);
		}
		return s;
	}

	/**
	 * 替换字符缓冲中所有的标签
	 * 
	 * @param strb
	 *            缓冲
	 * @param sStr
	 *            原字符
	 * @param nString
	 *            新字符
	 * @return
	 */
	public static StringBuffer replaceAll(StringBuffer strb, String sStr, String nString)
	{
		int start = 0;
		while ((start = strb.indexOf(sStr,start)) > -1) {
			strb.replace(start,start + sStr.length(),nString);
			start = start + nString.length();
		}
		return strb;
	}

	/**
	 * 格式话法规，论文，法律之星专用
	 * 
	 * @param strb
	 *            需要格式的字符缓冲
	 * @return
	 */
	public static StringBuffer txtFormat(StringBuffer strb)
	{
		String LineStr = "";
		int s0 = 0;
		int s1 = 0;
		int s2 = 0;
		int s3 = 0;
		StringBuffer tmpBuffer = new StringBuffer();
		String lineSpr = System.getProperty("line.separator");
		while (strb.indexOf(lineSpr) > -1) {
			LineStr = strb.substring(0,strb.indexOf(lineSpr)); // 取一行
			strb.delete(0,strb.indexOf(lineSpr) + lineSpr.length()); // 删除这一行
			s0 = LineStr.indexOf("    "); // 四个空格
			s1 = LineStr.indexOf("      "); // 六个
			s2 = LineStr.indexOf("                                    "); // 36个
			s3 = LineStr.indexOf("<pre>");

			if (s3 == 0) {
				tmpBuffer.append(LineStr);
				while (strb.indexOf(lineSpr) > -1) {
					LineStr = strb.substring(0,strb.indexOf(lineSpr)); // 取一行
					strb.delete(0,strb.indexOf(lineSpr) + lineSpr.length()); // 删除这一行
					s3 = LineStr.indexOf("</pre>");
					tmpBuffer.append(LineStr + lineSpr);
					if (s3 == 0) {
						break;
					}
				}
			}

			if (s0 == 0) {
				if (s1 == 0) {
					if (s2 == 0) {
						tmpBuffer.append("<div align=right>" + LineStr.trim() + "</div>");
					}
					else {
						tmpBuffer.append("<div  align=center><strong>" + LineStr.trim() + "</strong></div>");
					}
				}
				else {
					tmpBuffer.append("　　" + LineStr.trim() + lineSpr + "<br>");
				}
			}
			else {
				tmpBuffer.append(LineStr + lineSpr + "<br>");
			}

			// tmpBuffer.append(LineStr);
		}
		return tmpBuffer;
	}



	// 过滤网页代码 只保留数字
	public static String rmHtml2(String str)
	{
		if (str == null || str.equals("")) {
			str = "";
		}
		String regEx = "[=\\'^\"./%;&<>(A-Z)(a-z)]"; // 表示一个或多个a\p{Punct}

		Pattern p = Pattern.compile(regEx);

		Matcher m = p.matcher(str);

		str = m.replaceAll("");
		
		
		return str;
	
	}

	public static int isNumber(String s)
	{
		int tempid = 0;
		try {
			tempid = Integer.parseInt(s);
		}
		catch (NumberFormatException e) {
			tempid = 0;
		}
		return tempid;
	}

	public static void test(int arr[])
	{
		int[] tempArr = new int[] { 1, 23, 4, 100, 222, 21 };
		// arr = new int [tempArr.length];
		for (int i = 0; i < tempArr.length; i++) {
			arr[i] = tempArr[i];
		}
	}
	
	//获得系统时间 修整squid GMT bug
	public static String getNewTime()
	{
		String nowtime = "";
		Calendar Datenow = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat formatter2 = new SimpleDateFormat("Z");
		String tzone = formatter2.format(Datenow.getTime());
		
		//不是东八区 beijing时间
		if (tzone.equals("+0000")) {
			Datenow.add(Calendar.HOUR,+8);	//+8小时
			nowtime = formatter.format(Datenow.getTime());
		}else
		{
			nowtime = formatter.format(Datenow.getTime());
		}
		
		return nowtime;
	}
	
	/*写配置文件*/
	public void WriteLog(String c1,String c2,String c3,String c4,String indexType) throws IOException
	{
		//synchronized (this){
		String path = getClass().getResource("/updatelog.properties").getPath();
		
		GetProperties getProps = new GetProperties(path);
		

	    getProps.setKeyValue("t_news",c1,"",path);
	    getProps.setKeyValue("t_51site",c2,"",path);
	    getProps.setKeyValue("t_51article",c3,"",path);
	    getProps.setKeyValue("t_51bbs",c4,"",path);
	    getProps.setKeyValue("indexType",indexType,"Updatelog c_id value",path);
	    getProps.close();

		//}
		//System.out.println(path);

	}
	
	
	/* 重置配置文件,恢复成重新做索引状态 */
	
	public void ResetLog() throws IOException
	{
		//synchronized (this){
			
		String path = getClass().getResource("/updatelog.properties").getPath();
		
		GetProperties getProps = new GetProperties(path);

	    getProps.setKeyValue("t_news","0","",path);
	    getProps.setKeyValue("t_51site","0","",path);
	    getProps.setKeyValue("t_51article","0","",path);
	    getProps.setKeyValue("t_51bbs","0","",path);
	    getProps.setKeyValue("indexType","true","Updatelog c_id value",path);
	    getProps.close();
	    
		//}
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args)
	{
		String d = "2009-10-23 21:35:29";
		System.out.println(d.substring(11, 13));
		System.out.println(d.substring(14, 16));
		
		// Tools tools1 = new Tools();
		// System.out.println(Tools.dateToStr(new Date(),"yyyy-MM-dd
		// hh:MM:ss"));
		// System.out.println(Tools.strToDate(2003,12,23));
		// System.out.println(Tools.trimTxt(Tools.readFile("d:/test/chl001s232.txt"),15,
		// 20));
		// mkDir("d:/test/test/test/test/test/test/test");
		// System.out.println(xmlSpecial("<安徽大学>法律评论"));
		/*
		 * int[] arr = new int[] { 1, 4, 7, 2, 35, 3, 45, 33}; int[] arr1 = new
		 * int[] { 1, 4, 2, 33, 33}; //arr=Tools.delArr(arr,2);
		 * Arrays.sort(arr1); arr = Tools.getDiff(arr, arr1);
		 * Tools.printArr(arr); //Arrays.sort(arr); // Tools.printArr(arr);
		 */
		// System.out.println(Tools.rmHtml2(
		// "<a href='/showtxt?的' >中华人民共和国兵役法</a><br>...治县、市、市辖区的人民政府给予补助。"));
		try {
			// String str = Tools.readFile("d:/pie.xml", "utf-8").toString();
			// System.out.println(str);
			// Tools.writeFile("d:/tt.xml", str, "utf-8");
			//float p = 308;
			//Tools.toZipJpg("e:\\temp\\3.jpg","e:\\temp\\308x308_3.jpg",p);
		}
		catch (Exception ex) {
		}
	}

	/**
	 * 生成图片所略图 oldpath原图地址 savepath缩略图地址 pic_w缩略图宽度
	 * 
	 * @param oldpath
	 * @param savepath
	 * @float pic_w
	 * @return
	 */

	public static void toZipJpg(String oldpath, String savepath, float pic_w) throws Exception
	{

		java.io.File objPic = new java.io.File(savepath); // 判断有无图片,也是缩略图保存路径
		String picname = "";

		try {

			if (oldpath.indexOf("/") > -1) {
				picname = oldpath.substring(oldpath.lastIndexOf("/") + 1,oldpath.length()); // linux路径判断
				savepath = savepath.substring(0,savepath.lastIndexOf("/"));
			}
			else {
				picname = oldpath.substring(oldpath.lastIndexOf("\\") + 1,oldpath.length()); // win路径判断
				savepath = savepath.substring(0,savepath.lastIndexOf("\\"));
			}

			if (!objPic.exists()) { // 如果缩略图找不到
				//System.out.println("11");
				java.io.File file = new java.io.File(oldpath); // 读入原图文件

				File saveFile = new java.io.File(savepath); // 保存地址判断
				if (!saveFile.exists()) {
					// System.out.println("没有文件夹");
					//saveFile.mkdir();
				}
				Image src = null;
				src = javax.imageio.ImageIO.read(file); // 构造Image对象

				float tagsize = pic_w;
				int old_w = src.getWidth(null); // 得到源图宽
				int old_h = src.getHeight(null);// 得到源图长
				int new_w = 0;
				int new_h = 0; 
				int tempsize;
				if(old_w<tagsize){tagsize=old_w;}//如果是小图，按原比例压缩
				
				float tempdouble;
				if (old_w > old_h) {
					tempdouble = old_w / tagsize;
				}
				else {
					tempdouble = old_h / tagsize;
				}
				new_w = Math.round(old_w / tempdouble);
				new_h = Math.round(old_h / tempdouble); // 计算新图长宽
				BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
				tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); // 绘制缩小后的图

				javax.imageio.ImageIO.write(tag,"jpg",new File(saveFile,"308x308_"+picname));
				tag = null;

			}
		}
		catch (IOException ex) {
			System.out.println("toZipJpg is error");
		}

	}

	
	/**
	 * 把字符窜里面的开始标签为startToken、结束标签为endToken,的字符窜替换为rplStr
	 * 
	 * @param strb
	 *            字符窜缓冲
	 * @param startToken
	 *            开始标签
	 * @param endToken
	 *            结束标签
	 * @param rplStr
	 *            需要替换的字符窜
	 * @return 返回替换好的字符缓冲
	 */
	public static StringBuffer replaceStrToken(StringBuffer strb,
			String startToken, String endToken, String rplStr) {
		try {
			strb.replace(strb.indexOf(startToken) + startToken.length(), strb
					.indexOf(endToken), rplStr);

		} catch (Exception e) {
			System.out.println("Tools.replaceStrToken() err:" + e);
		}
		return strb;

	}

	/**
	 * 把字符窜里面的开始标签为startToken、结束标签为endToken,的字符窜替换为rplStr
	 * 
	 * @param strb
	 *            字符窜缓冲
	 * @param startToken
	 *            开始标签
	 * @param endToken
	 *            结束标签
	 * @param rplStr
	 *            需要替换的字符窜
	 * @return 返回替换好的字符缓冲
	 */
	public static StringBuffer replaceStrTokenAll(StringBuffer strb,
			String startToken, String endToken, String rplStr) {
		try {
			int start = 0;
			while ((start = strb.indexOf(startToken, start)) >= 0) {
				strb.replace(start + startToken.length(), strb.indexOf(
						endToken, start), rplStr);
				start = strb.indexOf(endToken, start);
			}

		} catch (Exception e) {
			System.out.println("Tools.replaceStrToken() err:" + e);
		}
		return strb;

	}
	
	  public static String getRootPath(){   
	         //因为类名为"Application"，因此" Application.class"一定能找到   
	         String result = Tools.class.getResource("Tools.class").toString();   
	         int index = result.indexOf("WEB-INF");   
	         if(index == -1){   
	             index = result.indexOf("bin");   
	         }   
	         result = result.substring(0,index);   
	         if(result.startsWith("jar")){   
	             // 当 class文件在jar文件中时，返回"jar:file:/F:/ ..."样的路径    
	             result = result.substring(10);   
	         }else if(result.startsWith("file")){   
	             // 当 class文件在class文件中时，返回"file:/F:/ ..."样的路径    
	             result = result.substring(6);   
	         }   
	         if(result.endsWith("/"))result = result.substring(0,result.length()-1);//不包含最后的"/"   
	         return result;   
	     }
	
	
}
